package com.chromatic.competition.view.recruitment;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.chromatic.competition.R;
import com.chromatic.competition.model.UserPost;
import com.chromatic.competition.utils.DatabaseHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Locale;

public class PostActivity extends AppCompatActivity {
    private EditText categoryEditText;
    private EditText competitionNameEditText;
    private EditText postContentEditText;
    private Button startTimeButton;
    private Button endTimeButton;
    private EditText expenseEditText;
//    private EditText isExpiredEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);

        categoryEditText = findViewById(R.id.editTextCategory);
        competitionNameEditText = findViewById(R.id.editTextCompetitionName);
        postContentEditText = findViewById(R.id.editTextPostContent);
        startTimeButton = findViewById(R.id.buttonStartTime);
        endTimeButton = findViewById(R.id.buttonEndTime);
        expenseEditText = findViewById(R.id.editTextExpense);
//        isExpiredEditText = findViewById(R.id.editTextIsExpired);
        Button submitButton = findViewById(R.id.buttonSubmit);

        startTimeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDateTimePicker(startTimeButton);
            }
        });

        endTimeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDateTimePicker(endTimeButton);
            }
        });

        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 从EditText中获取用户填写的内容
                int userId = getCurrentUserId();
                String category = categoryEditText.getText().toString();
                String competitionName = competitionNameEditText.getText().toString();
                String postContent = postContentEditText.getText().toString();
                String startTime = startTimeButton.getText().toString();
                String endTime = endTimeButton.getText().toString();
                double expense = Double.parseDouble(expenseEditText.getText().toString());
//                boolean isExpired = Integer.parseInt(isExpiredEditText.getText().toString()) == 1;
                boolean isExpired = false;

                // 创建Post对象
                UserPost userPost = new UserPost(userId, category, competitionName, postContent,
                        String.valueOf(LocalDateTime.now()), startTime, endTime,
                        expense, isExpired);

                // 将Post对象保存到数据库中
                new SavePostTask().execute(userPost);
            }
        });

        ImageView backButton = findViewById(R.id.backButton);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed(); // 调用系统返回操作
            }
        });
    }

    private void showDateTimePicker(final Button button) {
        final Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        DatePickerDialog datePickerDialog = new DatePickerDialog(PostActivity.this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        TimePickerDialog timePickerDialog = new TimePickerDialog(PostActivity.this,
                                new TimePickerDialog.OnTimeSetListener() {
                                    @Override
                                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                        calendar.set(Calendar.YEAR, year);
                                        calendar.set(Calendar.MONTH, monthOfYear);
                                        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                                        calendar.set(Calendar.MINUTE, minute);

                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                                        String datetime = sdf.format(calendar.getTime());

                                        button.setText(datetime);
                                    }
                                }, hour, minute, true);
                        timePickerDialog.show();
                    }
                }, year, month, day);
        datePickerDialog.show();
    }

    private int getCurrentUserId() {
        SharedPreferences prefs = getSharedPreferences("login_info", Context.MODE_PRIVATE);
        String userJson = prefs.getString("user", "");
        JSONObject userObject = null;
        try {
            userObject = new JSONObject(userJson);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        try {
            return Integer.parseInt(userObject.getString("user_id"));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressLint("StaticFieldLeak")
    private class SavePostTask extends AsyncTask<UserPost, Void, Boolean> {

        @Override
        protected Boolean doInBackground(UserPost... userPosts) {
            UserPost userPost = userPosts[0];
            Connection connection = null;
            PreparedStatement preparedStatement = null;

            try {
                // 连接到数据库
                connection = DatabaseHelper.connect();

                // 创建并执行插入语句
                String query = "INSERT INTO user_post (user_id, category, competition_name, post_content, post_time, start_time, end_time, expense, is_expired) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
                preparedStatement = connection.prepareStatement(query);
                preparedStatement.setInt(1, userPost.getUserId());
                preparedStatement.setString(2, userPost.getCategory());
                preparedStatement.setString(3, userPost.getCompetitionName());
                preparedStatement.setString(4, userPost.getPostContent());
                preparedStatement.setString(5, userPost.getPostTime());
                preparedStatement.setString(6, userPost.getStartTime());
                preparedStatement.setString(7, userPost.getEndTime());
                preparedStatement.setDouble(8, userPost.getExpense());
                preparedStatement.setBoolean(9, userPost.isExpired());
                preparedStatement.executeUpdate();

                return true;
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            } finally {
                // 关闭数据库连接和资源
                DatabaseHelper.close(preparedStatement);
                DatabaseHelper.close(connection);
            }
        }

        @Override
        protected void onPostExecute(Boolean success) {
            if (success) {
                // 提示保存成功
                Toast.makeText(PostActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                finish(); // 关闭Activity
            } else {
                // 提示保存失败
                Toast.makeText(PostActivity.this, "发布失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}